#ifndef COMMAPPLY_H
#define COMMAPPLY_H

#include "stdint.h"

typedef enum
{
    ApplyDevInfoCrc = 0, //设备资源CRC信息
}ApplyDevInfo;

typedef enum
{
    ApplyParaInfo = 1, //信息参数
    ApplyParaStore = 2, //存储参数
    ApplyParaRun = 3, //运行参数
    ApplyParaStatus = 4, //状态参数
}ApplyPara;

typedef enum
{
    ApplyOperateHardwareReset = 2, //硬重启
    ApplyOperateSoftwareReset = 3, //软重启
}ApplyOperate;

typedef enum
{
    ApplyCmdReadInfo = 0x01,        //读取信息
    ApplyCmdReadMeter,       
    ApplyCmdReadSignal,    
    ApplyCmdReadSample,       //读取采样数据
    ApplyCmdReadMap,
    ApplyCmdReadPID,
    ApplyCmdWriteMap,
    ApplyCmdReadPara,        //读取参数
    ApplyCmdWritePara,       //写入参数
    ApplyCmdWritePID = 10,
    ApplyCmdReadWave,
    ApplyCmdReadPIDValue,
    ApplyCmdOutTest, //输出测试
    
    ApplyCmdUpdateApp = 0x1e,       //更新app固件
    ApplyCmdOperate = 0x1f,         //操作
}ApplyCmdType;

typedef enum
{
    ApplyResultFailure = -2, //正确数据，操作失败
    ApplyResultErr = -1, //错误数据
    ApplyResultNoUse = 0, //不相关数据
    ApplyResultOK = 1, //正确数据，已结束
    ApplyResultWait = 2, //正确数据，未结束
}ApplyResult;

typedef union
{
    struct
    {
        uint8_t function:5; //功能
        uint8_t master:1; //上下行标识，1表示来自上位机数据
        uint8_t muti_page:1; //多页标识
        uint8_t err:1; //错误标识
    };
    uint8_t cmd;
}ApplyCmd;

typedef struct
{
    ApplyCmd cmd; //命令
    uint8_t id;
    uint8_t totalPage; //总页数
    uint8_t currentPage; //当前页数
}ApplyDataHeader;

typedef void (*commapply_send)(uint8_t *data, uint16_t len);

typedef struct _CommApply
{
    int dataSendLenMax;
    ApplyDataHeader header;
    uint8_t *tx_buff;
    uint16_t tx_buff_len;
    uint8_t *buff;
    uint8_t *rx_data;
    uint8_t data[1024];  //应用数据
    uint16_t tx_dataLen;
    uint16_t rx_dataLen;
    uint8_t recvComplete; //接受完毕
    commapply_send send; 
}CommApply;

#define TOOL_UD_IDLE			(0) //空闲状态
#define TOOL_UD_START_DOWN		(1) //开始下载
#define TOOL_UD_ERASE_FLASH		(2) //擦除FLASH
#define TOOL_UD_WRITE_DATA		(3) //写FLASH
#define TOOL_UD_READ_DATA		(4) //读FLASH
#define TOOL_UD_RUN_PROG		(5) //启动程序
#define TOOL_UD_END_DOWN		(6) //结束下载

typedef struct
{
    uint8_t id;
    uint8_t cmd;
    uint16_t frame_len_max;
    uint16_t current_no;
    uint32_t data_len;
    uint32_t data_len_recv;
}app_update_t;

extern int32_t protocol_decode(CommApply *comm_apply, uint8_t *data, uint16_t len);
extern void commApplyInit(CommApply *comm_apply, uint8_t *tx_buff);
#endif // COMMAPPLY_H